<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/3/14
 * Time: 9:35
 */

namespace app\api\controller;

use app\admin\controller\BaseAdminController;
use app\api\model\User;
use app\api\validate\LoginValidate;
use app\BaseController;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Response;

class Login extends BaseController
{
    /**
     * 登录
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function login(): Response
    {
        $param = request()->param();
        validate(LoginValidate::class)->scene("login")->check($param);
        $info = User::where('user_name', $param['user_name'])->find();
        if (!$info) return $this->error("用户不存在");
        if ($info->status != 1) return $this->error("被禁用用户");
        if (md5(request()->param("password")) != $info->password) return $this->error("用户或密码错误");
        $userInfo = $info->toArray();
        unset($userInfo['password']);
        $token = getToken($info->id, 1); // 生成JWT令牌
        return $this->success('成功', compact("userInfo", "token"));
    }
}